package com.example.swing;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.niit.dao.StudentMapper;
import com.niit.entity.Student;
import com.niit.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;


public class AddUserWindow extends JFrame {
    private JTextField snameField, spasswordField, sgenderField, sbatchField;
    private JButton addButton;

    public AddUserWindow() {
        setTitle("Add User");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        snameField = new JTextField(20);
        spasswordField = new JTextField(20);
        sgenderField = new JTextField(20);
        sbatchField = new JTextField(20);
        addButton = new JButton("Add User");

        add(new JLabel("Name:"));
        add(snameField);
        add(new JLabel("Password:"));
        add(spasswordField);
        add(new JLabel("Gender:"));
        add(sgenderField);
        add(new JLabel("Batch:"));
        add(sbatchField);
        add(addButton);

        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String sname = snameField.getText();
                String spassword = spasswordField.getText();
                String sgender = sgenderField.getText();
                String sbatch = sbatchField.getText();

                try (SqlSession session = MybatisUtil.getSqlSession()) {
                    StudentMapper mapper = session.getMapper(StudentMapper.class);

                    Student student = new Student("1002",sname, spassword, sgender, sbatch);
                    mapper.addStudent(student);
                    session.commit();
                    JOptionPane.showMessageDialog(AddUserWindow.this, "User added successfully!");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(AddUserWindow.this, "Error adding user: " + ex.getMessage());
                }
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            AddUserWindow window = new AddUserWindow();
            window.setVisible(true);
        });
    }
}